<template>
	<div id="bg" class="w-h-100" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex">
			<el-card class="box-card" shadow="never" :body-style="{ paddingBottom: '0' }">
				<search ref="searchRef" v-bind="troubleSearch">
					<template #footer="scope">
						<el-button type="primary" icon="ele-Search" @click="query"> {{ $t('qEh3zD5bC8bZb4bLvFe29') }} </el-button>
						<el-button icon="ele-Plus" type="primary" @click="add" v-if="$hasPer('trouble:add')"> {{ $t('wnpevud10fwvwhDyynC4A') }} </el-button>
					</template>
				</search>
			</el-card>

			<el-card class="w-h-100 flex-1 box-card" style="margin-top: 16px" shadow="never" :body-style="{ paddingBottom: '0' }">
				<inscroll-table :data-list="list" v-bind="troubleTableConfig" :dataCount="Number(totalRows)" :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange">
					<template #n_AccidentType="scope">
						<div>
							{{
								scope.row.n_AccidentType == 1
									? $t('6OXRd46kqWcjgKWikLab')
									: scope.row.n_AccidentType == 2
									? $t('v3z9u2qGz6rkAiKlOMqmw')
									: scope.row.n_AccidentType == 3
									? $t('mou2x2mSTasl8p_6V93Oc')
									: $t('bgVvcSvUalDBrkLfHmMgm')
							}}
						</div>
					</template>
					<template #n_AccidentLevel="scope">
						<div>
							{{
								scope.row.n_AccidentLevel == 1
									? $t('ergqfyNSpLgNxuuD7GyAz')
									: scope.row.n_AccidentLevel == 2
									? $t('oglxx6bPsV5ZSbNsuceBs')
									: scope.row.n_AccidentLevel == 3
									? $t('oPywhZlVTzfbU7zyP3io')
									: $t('dgNnBtN1BUk1ZjMEum4bH')
							}}
						</div>
					</template>
					<template #file="scope">
						<div style="cursor: pointer" @click="fileClick(scope.row.v_FilePath)">{{ scope.row.v_FilePath?.length > 0 ? $t('2KyEk7Ir2Lz3bN9ByjSaE') : $t('66gSt7xsIbieLa59Td1H') }}</div>
					</template>
					<template #operation="scope">
						<div>
							<el-button
								icon="ele-Document"
								@click="
									() => {
										detailAction(scope.row);
									}
								"
								type="primary"
								size="small"
								text
							>
								{{ $t('ucC9qxHvkvdh9OGEo1pn') }}
							</el-button>
							<el-button
								icon="ele-Edit"
								@click="
									() => {
										changeAction(scope.row);
									}
								"
								type="primary"
								size="small"
								text
								v-if="$hasPer('trouble:change')"
							>
								{{ $t('kiUkiqa3h0HLymgh7eEb') }}
							</el-button>
							<!-- <el-button icon="ele-Folder" v-if="scope.row.v_FilePath?.length > 0" type="success" @click="pushFile(scope.row.v_FilePath)" text size="small">{{
								$t('s4KbtSrTfOzuWyRcHgTxx')
							}}</el-button> -->
							<el-button
								icon="ele-Delete"
								@click="
									() => {
										deleteAction(scope.row);
									}
								"
								type="danger"
								size="small"
								text
								v-if="$hasPer('trouble:delete')"
							>
								{{ $t('mkwlMbm3qr88f0XxV9Pje') }}
							</el-button>
						</div>
					</template>
				</inscroll-table>
			</el-card>
		</div>
		<trouble-form ref="formRef" @submit="(param: any) => submitHandle(param)" @refresh="getData"></trouble-form>
		<VModel :fileInfo="fileInfo" :isModelDialog="isModelDialog" @cancelModelClick="cancelModelClick" />
	</div>
</template>

<script lang="ts" setup>
import { inscrollTable, troubleTableConfig } from './config/table/index';
import { search, troubleSearch } from './config/search/index';
import { ref } from 'vue';
import troubleForm from './component/add-edit-trouble-removal.vue';
import { IPostTroubleType } from '/@/types/ys/index';
import getStaticTableData from '/@/utils/staticGetTableData';
import { getTroubleList, postTrouble, postChangeTrouble, postDeleteTrouble } from '/@/api/safety-play/index';
import { ElMessageBox } from 'element-plus';
import { NORMSTARTTIMEfilter } from '/@/utils/hook/getDate';
import commonRequest from '/@/api/common/common';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';

import VModel from '../components/v-model.vue';

import eventBus from '/@/utils/eventBus';

const { proxy } = useCurrentInstance();
const $t = proxy.$t;

const formRef = ref();

const { list, totalRows, handleSizeChange, handleCurrentChange, getData } = getStaticTableData(getTroubleList, {}, troubleSearch.searchObj);

let isChange = false;
let currentSelectData: any;
//附件删除后刷新列表
eventBus.on('getData', getData);
const detailAction = (data: any) => {
	isChange = false;
	formRef.value.detail(data);
};
const changeAction = (data: any) => {
	currentSelectData = data;
	isChange = true;
	formRef.value.change(data);
};

const deleteAction = (data: any) => {
	ElMessageBox.confirm($t('itYcbTIj20MmWuPdBMgvd'), $t('nHdM3UcfLoZbHyqgSa3cx'), {
		confirmButtonText: $t('cpmrq09Mw3tfVmwWGsZzb'),
		cancelButtonText: $t('wFa44E4Iz025Ha2gYeDop'),
		type: 'warning',
		center: true,
	})
		.then(async () => {
			await postDeleteTrouble({
				n_Id: data.n_Id,
			});
			getData();
		})
		.catch(() => {});
};

const query = () => {
	getData();
};

/**
数组过滤,originalArray 是源数组, [ {
            "id": 419084105420875,
            "name": "建兵",
            "orgId": 409189188800581,
            "orgName": "广东鑫茂彩光板1组"}],

			nameArray["建兵"],查找两个数组中相匹配的元素返回一个集合
 */
function matchNames(originalArray: any, nameArray: any) {
	let result: any = [];
	originalArray.forEach((item: any) => {
		if (nameArray.includes(item.name.trim())) {
			// trim() is used to remove any extra spaces in the name
			result.push(item.id);
		}
	});
	return result;
}

const submitHandle = async (param: any) => {
	let changeEmpStr = [];
	let res = await commonRequest.getUserList();
	//通过名字找到对应的id
	changeEmpStr = matchNames(res.data, param.accientEmp);
	let tempFileID = 0;
	//新增时获取雪花id为filedId赋值
	if (!isChange) {
		let res = await commonRequest.getGenerateId();
		tempFileID = res.data;
	}

	const postData: IPostTroubleType = {
		N_ProjectId: isChange && currentSelectData.v_ProjectName == param.n_ProjectId ? currentSelectData.n_ProjectId : param.n_ProjectId,
		N_AccidentType: param.n_AccidentType,
		AccientEmp: changeEmpStr.join(),
		N_BlameEmp: isChange && currentSelectData.v_BlameEmpName == param.n_BlameEmp ? currentSelectData.n_BlameEmp : param.n_BlameEmp,
		D_AccidentTime: NORMSTARTTIMEfilter(param.d_AccidentTime),
		V_AccidentAddress: param.v_AccidentAddress,
		N_AccidentLevel: param.n_AccidentLevel,
		V_AfterContent: param.v_AfterContent,
		V_HandleMeasure: param.v_HandleMeasure,
		V_Remark: param.v_Remark,
		N_FileId: isChange ? currentSelectData.n_FileId : tempFileID,
	};
	let postFiles = [];
	for (let index = 0; index < formRef.value.fileList.length; index++) {
		postFiles.push(formRef.value.fileList[index].raw);
	}
	console.log('postFiles', postFiles);
	//多文件上传
	if (postFiles.length > 0) {
		let res = await commonRequest.postFilesData({
			sourceType: 'SMS',
			sourceId: postData.N_FileId,
			files: postFiles,
		});
	}

	if (isChange) {
		postData.n_Id = currentSelectData.n_Id;
		await postChangeTrouble(postData);
	} else {
		await postTrouble(postData);
	}

	getData();
};

const add = () => {
	isChange = false;
	formRef.value.addNew({});
};

const isModelDialog = ref(false);
const cancelModelClick = () => {
	isModelDialog.value = false;
};
const fileInfo = ref('');
/*** 查看文件 */
const fileClick = (val: any) => {
	if (val.length == 0 || val == null) {
		return;
	}
	isModelDialog.value = true;
	let setObj: any = {};
	setObj.titleInfo = $t('s4KbtSrTfOzuWyRcHgTxx');
	setObj.rectifyListArr = val;
	fileInfo.value = JSON.stringify(setObj);
};
</script>

<!-- scoped属性使style有自己独立的作用域(属性选择器实现 title[data-v-xxx]) -->
<style lang="scss" scoped>
#bg {
	:deep(.el-card__body) {
		height: 100%;
	}
}
</style>
